<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="uname" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="addChange(index)">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in list" :key="index">
          <td>{{ index + 1 }}</td>
          <td>{{ item.uname }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.gender }}</td>
          <td>
            <button @click="del(index)">删除</button>
            <button @click="changed(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      list: JSON.parse(localStorage.getItem('students-list')) || [],
      uname: '',
      age: 0,
      gender: '',
      index: '',
    }
  },
  // 监听list
  watch: {
    list: {
      deep: true,
      handler() {
        localStorage.setItem('students-list', JSON.stringify(this.list))
      },
    },
  },
  methods: {
    // 点编辑回显
    changed(index) {
      // console.log(this.list)
      this.uname = this.list.at(index).uname
      this.age = this.list.at(index).age
      this.gender = this.list.at(index).gender
      this.index = this.list.index
    },
    // 删除
    del(index) {
      // console.log(index)
      // this.list = this.list.filter((item) => item.index !== index)
      this.list.splice(index, 1)
    },
    // 添加或修改
    addChange() {
      // 判断是否合法
      if (this.age <= 0 || !this.uname || !this.gender) {
        return alert('输入不合法')
      }
      if (this.index !== '') {
        this.list.splice(this.index, 1)
        this.list.splice(this.index, 0, {
          uname: this.uname,
          age: this.age,
          gender: this.gender,
        })
      } else {
        this.list.push({
          uname: this.uname,
          age: this.age,
          gender: this.gender,
        })
      }
      // 提交后清空
      this.uname = ''
      this.age = 0
      this.gender = ''
      this.index = ''
    },
  },
}
</script>
